<?php

namespace App\Tools;

class AliSms
{

//    public static $accessKeyId     = "LTAI4GCAXZ1zZu45HUDmo4C9";
//    public static $accessKeySecret = "uOgi13U2mxfO83yS6soNuWagfW8yey";
//    public static $SignName        = "益恩喜";

    public static $accessKeyId = "LTAI5tL4U3giDQXosjhit8s7";
    public static $accessKeySecret = "W6C58jyj4nxYIBiBchvzwoauIROEqJ";
    public static $SignName = "亿恩鑫";

    /**
     * 短信发送列表
     *
     * @param [type] $mobile
     * @param [type] $type
     * @param [type] $code
     * @param [type] $name
     * @return void
     */
    public static function sendList($mobile, $type = 1, $name = '', $dataArr = [])
    {
        $re = true;
        if ($mobile) {
            switch ($type) {
                case '1':
                    // 【益恩喜】尊敬的代理商，您的资质升级已审核成功，请登陆查看。
//                    $re = self::sendAppSMS($mobile, 'SMS_190276738', ['code' => $name]);
                    $re = self::sendAppSMS($mobile, 'SMS_216831430', ['code' => $name]);
                    break;
                case '2':
                    // 【益恩喜】尊敬的客户，您的订单OD20001001因账户余额不足，无法发货，请及时充值。
//                    $re = self::sendAppSMS($mobile, 'SMS_190281755', ['order' => $name]);
                    $re = self::sendAppSMS($mobile, 'SMS_216841182', ['order' => $name]);
                    break;
                case '3':
                    // 【益恩喜】尊敬的客户，您的订单OD20001001因余额不足，超期系统已经自动取消。
//                    $re = self::sendAppSMS($mobile, 'SMS_190276751', ['order' => $name]);
                    $re = self::sendAppSMS($mobile, 'SMS_216831385', ['order' => $name]);
                    break;
                case '4':
                    // 【益恩喜】尊敬的客户，您的订单编号OD20001001已发货，快递公司为1111，快递单号为222，请注意查收。
//                    $re = self::sendAppSMS($mobile, 'SMS_190281754', ['orderNumber' => $name, 'expressCompany' => $dataArr['expressCompany'], 'espressOrder' => $dataArr['espressOrder']]);
                    $re = self::sendAppSMS($mobile, 'SMS_216826425', ['orderNumber' => $name, 'expressCompany' => $dataArr['expressCompany'], 'espressOrder' => $dataArr['espressOrder']]);
                    break;
                case '5':
                    // 【益恩喜】您已成功注册成为ENC加盟代理商。账号为：OD20001001，密码为：1111。请妥善保管您的个人信息，切勿告诉他人  SMS_190276738
//                    $re = self::sendAppSMS($mobile, 'SMS_190281751', ['user' => $name, 'password' => $dataArr['password']]);
                    $re = self::sendAppSMS($mobile, 'SMS_216831434', ['user' => $name, 'password' => $dataArr['password']]);
                    break;
                default:
                    # code...
                    break;
            }
            return $re;
        }
        return false;
    }


    //App短信发送
    public static function sendAppSMS($mobile, $TemplateCode, $tempInfo = [])
    {

        $params = array();
        //手机号
        $params["PhoneNumbers"] = $mobile;
        //签名
        $params["SignName"] = self::$SignName;
        //登陆注册模板
        $params["TemplateCode"] = $TemplateCode;
        //设置模板参数, 假如模板中存在变量需要替换则为必填项
        if ($tempInfo) {
            $params['TemplateParam'] = $tempInfo;
        }
        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
        // var_dump($params);
        $paramsArr = ["RegionId" => "cn-hangzhou", "Action" => "SendSms", "Version" => "2017-05-25"];
        // 此处可能会抛出异常，注意catch
        $content = self::request("dysmsapi.aliyuncs.com", array_merge($params, $paramsArr));
        // var_dump($content);exit;
        return $content;
    }

    /**
     * 请求函数
     * @param type $domain
     * @param type $params
     * @param type $security
     * @return boolean
     */
    public static function request($domain, $params, $security = false)
    {
        saveLog($params, 'Aliyun');

        $accessKeyId = self::$accessKeyId;
        $accessKeySecret = self::$accessKeySecret;

        $apiParams = array_merge(array(
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
            "SignatureVersion" => "1.0",
            "AccessKeyId" => $accessKeyId,
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
            "Format" => "JSON",
        ), $params);
        ksort($apiParams);

        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . self::encode($key) . "=" . self::encode($value);
        }

        $stringToSign = "GET&%2F&" . self::encode(substr($sortedQueryStringTmp, 1));

        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));

        $signature = self::encode($sign);

        $url = ($security ? 'https' : 'http') . "://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}";

        try {
            $content = self::fetchContent($url);
            saveLog($content, 'Aliyun');
            // var_dump($content);exit;
            $re = json_decode($content, true);
            if ($re && $re['Message'] == 'OK' && $re['Code'] == 'OK') {
                return true;
            }
        } catch (\Exception $e) {
            return false;
        }
        return false;

        /**
         * 返回数据
         * {#201 ▼
         * +"Message": "OK"
         * +"RequestId": "2F3EFE06-AEA2-4CEE-ADAD-AA189C43C1F3"
         * +"BizId": "410218722821144862^0"
         * +"Code": "OK"
         * }
         */
    }

    private static function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);
        return $res;
    }

    private static function fetchContent($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "x-sdk-client" => "php/2.0.0",
        ));

        if (substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $rtn = curl_exec($ch);

        if ($rtn === false) {
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);

        return $rtn;
    }

    private static function random($length = 6, $numeric = 0)
    {
        PHP_VERSION < '4.2.0' && mt_srand((float)microtime() * 1000000);
        if ($numeric) {
            $hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for ($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }
}
